package coder;

import java.io.File;
import java.io.FileOutputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import net.sf.lamejb.LameCodec;
import net.sf.lamejb.LamejbConfig;
import net.sf.lamejb.LamejbConfig.MpegMode;

import org.kc7bfi.jflac.apps.ExtensionFileFilter;
import org.kc7bfi.jflac.sound.spi.FlacAudioFileReader;
import org.kc7bfi.jflac.sound.spi.FlacFormatConversionProvider;

public class JFlacToMp3RecoderOld {
    
	public static final int DEFAULT_BITRATE = 256;
	public static final int DEFAULT_SAMPLERATE = 44100;
	
	public static void FlacToMp3(String from, String to){
		FlacToMp3(new File(from), new File(to),DEFAULT_BITRATE,DEFAULT_SAMPLERATE);
	}
	
	public static void FlacToMp3(File from, File to){
		FlacToMp3(from, to, DEFAULT_BITRATE,DEFAULT_SAMPLERATE);
	}
	
	public static  void FlacToMp3(String from,String to,int bitrate){
		FlacToMp3(new File(from), new File(to),bitrate);
	}
	
	public static  void FlacToMp3(File from,File to,int bitrate){
		FlacToMp3(from, to,bitrate,DEFAULT_SAMPLERATE);
	}
	
	public static void Flac2Mp3(String from, String to, int bitrate, int samplerate){
		FlacToMp3(new File(from), new File(to), bitrate, samplerate);
	}
	
	public static void FlacToMp3(File from, File to,int bitrate,int samplerate) {
		try {
			AudioInputStream flacInputStream = new FlacAudioFileReader().getAudioInputStream(from);
			AudioInputStream rawInputStream = new FlacFormatConversionProvider().getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, flacInputStream);
			FileOutputStream outStream = new FileOutputStream(to);
			LamejbConfig config = new LamejbConfig(samplerate, bitrate, MpegMode.STEREO, false);
			new LameCodec().encodeStream(rawInputStream, outStream, config);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		File from;
		File to;
		JFileChooser fc = new JFileChooser();
		fc.setMultiSelectionEnabled(false);
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);		
		fc.setCurrentDirectory(new File(System.getenv("USERPROFILE")+"/Desktop"));
		fc.setFileFilter(new ExtensionFileFilter(new String[]{"flac"}, "Free Loseless Codec Audio files"));
		fc.showOpenDialog(null);
		from = fc.getSelectedFile();
		if (from==null) System.exit(0);
		JOptionPane.showMessageDialog(null,"from "+from);	
		fc.setFileFilter(null);
		fc.showSaveDialog(null);
		to = fc.getSelectedFile();
		JOptionPane.showMessageDialog(null, "to "+to);
		new Thread(new Runnable() {
			@Override
			public void run() {
				JOptionPane.showMessageDialog(null, "Recoding started...");
			}
		}).start();
		JFlacToMp3RecoderOld.FlacToMp3(from, to);
		JOptionPane.showMessageDialog(null, "Recoding completed!)");
	}
}
